package br.com.obardavez.util.impl;

import br.com.obardavez.util.QueryUtil;

public class QueryUtilImpl implements QueryUtil {


	private static final long serialVersionUID = 1L;

	@Override
	public String createSelectMapClause(String entityName, String... fields) {
		StringBuilder fieldsMap = new StringBuilder(200);
		if (fields != null) {
			for (String field : fields) {
				fieldsMap.append(fieldsMap.length() == 0 ? "" : ",");
				fieldsMap.append(entityName + "." + field + " as " + field);
			}

			fieldsMap.insert(0, "new map(").append(")");
		}

		return fieldsMap.toString();
	}

	@Override
	public String groupOrFilters(StringBuilder whereClause) {
		return groupOrFilters(whereClause.toString());
	}

	@Override
	public String groupOrFilters(String whereClause) {
		final String AND_OPERATOR = " AND ";
		final String OR_OPERATOR = " OR ";

		final String REGEX = AND_OPERATOR.toLowerCase() + "|" + AND_OPERATOR;

		StringBuilder resultFilters = new StringBuilder(200);
		String[] andFilters = whereClause.split(REGEX);

		for (String andFilter : andFilters) {
			resultFilters.append(resultFilters.length() == 0 ? ""
					: AND_OPERATOR);
			if (andFilter.toUpperCase().contains(OR_OPERATOR)) {
				resultFilters.append("(").append(andFilter).append(")");
			} else {
				resultFilters.append(andFilter);
			}
		}

		return resultFilters.toString();
	}

	@Override
	public String createOrderByClause(String entityName, String... fields) {
		StringBuilder fieldsOrderBy = new StringBuilder(200);
		if (fields != null) {
			for (String field : fields) {
				fieldsOrderBy.append(fieldsOrderBy.length() == 0 ? "" : ",");
				fieldsOrderBy.append(entityName + "." + field);
			}

			fieldsOrderBy.insert(0, "ORDER BY ");
		}

		return fieldsOrderBy.toString();
	}

}
